<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/1
 * Time: 14:35
 */

namespace app\common\lib\pay;


use app\common\lib\aop\AopClient;
use app\common\lib\aop\request\{AlipayTradePagePayRequest,AlipayTradeAppPayRequest,AlipayTradeWapPayRequest};

class AliPay implements IPay
{
    const PRODUCT_CODE_APP = 1;
    const PRODUCT_CODE_WAP = 2;
    const PRODUCT_CODE_PC = 3;
    private static $ProductCodes = [
        self::PRODUCT_CODE_APP => 'QUICK_MSECURITY_PAY',
        self::PRODUCT_CODE_WAP => 'QUICK_WAP_WAY',
        self::PRODUCT_CODE_PC => 'FAST_INSTANT_TRADE_PAY',
    ];
    private static $Requests = [
        self::PRODUCT_CODE_APP => AlipayTradeAppPayRequest::class,
        self::PRODUCT_CODE_WAP => AlipayTradeWapPayRequest::class,
        self::PRODUCT_CODE_PC  => AlipayTradePagePayRequest::class
    ];

    private static $instance = null;
    public static function getInstance() {
        if (empty(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 下订单
     *
     * @param $out_trade_no string 订单号
     * @param $total_fee float 支付总金额
     * @param $body string 商品描述
     * @param $client_type integer 支付类型，比如 1-APP、2-微信/手机、3-PC
     * @param $client_ip string 支付的客户端实际IP
     * @param $detail string
     * @param null $ext
     * @return mixed
     */
    function unifiedOrder(
        $out_trade_no, $total_fee, $body, $client_type, $client_ip, $detail = '', $ext = null
    ) {

        $req = new self::$Requests[$client_type]();
        $req->setNotifyUrl(config('server.host') . '/callback/pay/alipay');
        $bizContent = [
            'body' => $body,
            'out_trade_no' => $out_trade_no,
            'subject' => $body.','.$detail,
            'total_amount' => $total_fee,
            'product_code' => self::$ProductCodes[$client_type] ?? self::PRODUCT_CODE_APP,
        ];
        $req->setBizContent(json_encode($bizContent, JSON_UNESCAPED_UNICODE));

        if (self::PRODUCT_CODE_APP == $client_type) {
            $re = AopClient::getInstance()->sdkExecute($req);
        } else {
            $re = AopClient::getInstance()->pageExecute($req);
        }

        return $re;
    }


    /**
     * 获取字段key，方便客户端调用
     *
     * @return string
     */
    function getKey()
    {
        return 'alipay';
    }
}